'''
- Encapsulate http cookie
- TODO:
	- parse "expires=Sat, 14-Feb-2009 10:56:46 GMT;"
	- parse domain from host
	- validate set-cookie from server
'''

import datetime
import pickle
import Cookie
import urlparse

from google.appengine.api import memcache

import domainhelper

COOKIE_SEP = ', '
EXPIRE_DATETIME_FMT = '%a, %d-%b-%Y %H:%M:%S GMT'

def join(left, right):
	return left + COOKIE_SEP + right

def strftime(time):
	return time.strftime(EXPIRE_DATETIME_FMT)

class SessionCookie(object):
	def __init__(self, session_id):
		self.session_id = session_id

	def output_matched(self, url):
		value = memcache.get(self.session_id)
		cookie = value and pickle.loads(value) or Cookie.BaseCookie()
		for k,morsel in cookie.items():
			expire_time = datetime.datetime.strptime(morsel['expires'], EXPIRE_DATETIME_FMT)
			if expire_time <= datetime.datetime.utcnow():
				del cookie[k]
		memcache.set(self.session_id, pickle.dumps(cookie))
		cookie_output = []
		split_result = urlparse.urlsplit(url)
		for k,morsel in cookie.iteritems():
			if split_result.hostname.lower().endswith(morsel['domain'].lower()) and split_result.path.startswith(morsel['path']):
				cookie_output.append(morsel.output(header='').lstrip())
		return COOKIE_SEP.join(cookie_output)

	def update(self, url, result):
		value = memcache.get(self.session_id)
		cookie = value and pickle.loads(value) or Cookie.BaseCookie()
		for k,v in result.headers.items():
			if 'set-cookie' in k.lower():
				# TODO: cannot parse expires
				cookie.load(v)
				del result.headers[k]
		split_result = urlparse.urlsplit(url)
		for k,morsel in cookie.iteritems():
			try:
				datetime.datetime.strptime(morsel['expires'], EXPIRE_DATETIME_FMT)
			except:
				morsel['expires'] = \
					(datetime.datetime.utcnow() + datetime.timedelta(days=14)).strftime(EXPIRE_DATETIME_FMT)
			if not morsel['path']:
				morsel['path'] = split_result.path
			if not morsel['domain']:
				morsel['domain'] = domainhelper.extract_domain(split_result.hostname)
		memcache.set(self.session_id, pickle.dumps(cookie))
